package com.kezesong.leasing.service;

import com.kezesong.leasing.common.CacheService;
import com.kezesong.leasing.common.Constant;
import com.kezesong.leasing.common.CookieUtils;
import com.kezesong.leasing.common.enums.ReturnCodeEnum;
import com.kezesong.leasing.common.exception.CommonException;
import com.kezesong.leasing.dto.SessionInfo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.ExecutionException;

@Component
public class SessionService {

    @Value("${domainName}")
    private String domainName;

    public String getWeixinSessionTicket(HttpServletRequest httpServletRequest) {
        String sessionTicket = CookieUtils.getCookie(Constant.WEIXIN_SESSION_TICKET, httpServletRequest);
        return sessionTicket;
    }

    public SessionInfo getSessionInfo(String sessionTicket) throws ExecutionException, CommonException {
        SessionInfo userLoginInfo = CacheService.getUserLoginInfo(sessionTicket);
        if (null == userLoginInfo){
            throw new CommonException(ReturnCodeEnum.SESSION_TIME_OUT);
        }
        return userLoginInfo;
    }

    public String createSession(SessionInfo sessionInfo) {
        String sessionId = CacheService.createLoginSesssion(sessionInfo);
        return sessionId;
    }

    public String refreshSession(SessionInfo newSessionInfo) {
        String sessionId = CacheService.createLoginSesssion(newSessionInfo);
        return sessionId;
    }

    public void writeWxLoginCookie(String sessionId, HttpServletResponse httpServletResponse){
        CookieUtils.WriteCookie(Constant.WEIXIN_SESSION_TICKET, sessionId, httpServletResponse, domainName);
    }
}
